import React, { useEffect, useMemo, useRef } from 'react'
import {
  View,
  Text,
  Image,
  StatusBar,
  StyleSheet,
  ImageBackground,
  Animated,
  Pressable,
  FlatList,
} from 'react-native'
import { common } from '../assets/style/common'
import useGetStatusBar from '../utils/useGetStatusBar'
import { LinearGradient } from 'expo-linear-gradient'
import { CategoryData } from '../assets/data/data'
import HomeSwiper from '../component/home/homeSwiper'
import SearchTxt from '../component/searchTxt'
import ListWrap from '../component/home/listWrap'
import Countdown from '../component/home/countdown'
import {
  TodayRecomment,
  ChildrenYongPing,
} from '../component/home/todayRecomment'
import ConditionWrap from '../component/home/conditionWrap'
import { RNBridgeModule } from '../native/index.js'
import { observer } from 'mobx-react-lite'
import { useStore } from '@/store'
let scrollVal = 0
const Home = function (props: any) {
  const [barHeight] = useGetStatusBar()
  const scrollY = useRef(new Animated.Value(0)).current
  const { HomeStore } = useStore()
  const flatListRef = useRef<FlatList>(null)
  useEffect(() => {
    scrollY.addListener(({ value }) => {
      scrollVal = value
      HomeStore.SET_SCROLL_TOP(value)
    })
    return () => {
      scrollY.removeAllListeners()
    }
  }, [])
  useEffect(() => {
    if (flatListRef.current) {
      HomeStore.SET_HOME_LIST_REF(flatListRef.current)
    }
    return () => {
      HomeStore.SET_HOME_LIST_REF(null)
    }
  }, [flatListRef.current])
  const bannerBgmColor = useMemo(() => {
    return scrollY.interpolate({
      inputRange: [0, 200 - barHeight],
      outputRange: [0, 1],
    })
  }, [scrollY, barHeight])
  const addressColor = useMemo(() => {
    return scrollY.interpolate({
      inputRange: [0, 200 - barHeight],
      outputRange: [0, 1],
      easing(input) {
        input = input < 1 ? (input <= 0 ? 1 : 1 - input) : 0
        return input
      },
    })
  }, [scrollY, barHeight])
  const marginLeft = useMemo(() => {
    return scrollY.interpolate({
      inputRange: [0, 200 - barHeight],
      outputRange: [0, 1],
      easing(input) {
        input = input < 1 ? (input <= 0 ? 0 : input * 30) : 30
        return input
      },
    })
  }, [scrollY, barHeight])
  const searchTop = useMemo(() => {
    return scrollY.interpolate({
      inputRange: [0, 200 - barHeight],
      outputRange: [10, -14],
      extrapolate: 'clamp',
    })
  }, [scrollY, barHeight])

  const listWrapRef = useRef<any>()
  const menulist = useMemo(() => CategoryData, []) // 分类

  function goCategory(id: any) {
    props.navigation.navigate('Category', {
      screen: 'CategoryIndex',
      params: { categoryId: id },
    })
  }
  function onScrollEndDrag(e: any) {
    var offsetY = e.nativeEvent.contentOffset.y //滑动距离
    var contentSizeHeight = e.nativeEvent.contentSize.height //scrollView contentSize高度
    var oriageScrollHeight = e.nativeEvent.layoutMeasurement.height //scrollView高度
    if (offsetY + oriageScrollHeight >= contentSizeHeight - 10) {
      listWrapRef.current.loadMore(11)
    }
  }

  function goTab(
    key:
      | 'RecommondTab'
      | 'ChildGoodTab'
      | 'SpecialTab'
      | 'SelectGoodTab'
      | 'DiscountReductionTab',
  ) {
    return () => {
      props.navigation.navigate('GoodSearchTab', { key })
    }
  }
  async function onTestParentFunc() {
    RNBridgeModule.createEvent('methodName', (eventId: string, arr: any[]) => {
      console.log('methodName', eventId, arr)
    })
    await RNBridgeModule.promiseMethod('promise')
  }
  function goCamera() {
    props.navigation.navigate('Camera')
  }
  function onPressTopMenu() {
    if (scrollVal > 200 - barHeight) {
      goCamera()
    } else {
      onTestParentFunc()
    }
  }
  return (
    <>
      <StatusBar
        translucent
        backgroundColor="rgba(0,0,0,0)"
        barStyle={'light-content'}
      />
      <FlatList
        style={styles.contain}
        showsVerticalScrollIndicator={false}
        stickyHeaderIndices={[0]}
        onMomentumScrollEnd={onScrollEndDrag}
        onScroll={Animated.event(
          [{ nativeEvent: { contentOffset: { y: scrollY } } }],
          { useNativeDriver: false },
        )}
        scrollEventThrottle={16}
        bounces={false}
        ref={flatListRef}
        data={[
          { type: 'header' },
          { type: 'swiper' },
          { type: 'categoryMenu' },
          { type: 'menuCard' },
          // { type: 'conditionWrap', },
          { type: 'listWrap' },
        ]}
        renderItem={({ item }) => {
          switch (item.type) {
            case 'header':
              return (
                <View
                  style={[
                    styles.header,
                    {
                      height: 48 + barHeight,
                      paddingLeft: 12,
                      paddingRight: 12,
                    },
                  ]}
                >
                  <Animated.View
                    style={[
                      styles.headerBgm,
                      {
                        opacity: bannerBgmColor,
                      },
                    ]}
                  >
                    <LinearGradient
                      start={{ x: 0.2, y: 0.3 }}
                      end={{ x: 0.8, y: 0.7 }}
                      colors={['#73d7f7', '#57aef0']}
                      style={{ width: '100%', height: '100%' }}
                    />
                  </Animated.View>
                  <Pressable onPress={onPressTopMenu} style={styles.dropAdd}>
                    <Animated.View
                      style={[
                        {
                          marginTop: barHeight,
                          opacity: addressColor,
                          height: 16,
                        },
                        common.flexCol,
                      ]}
                    >
                      <Text style={[styles.hI, { marginRight: 2 }]}>
                        &#xe62c;
                      </Text>
                      <Text style={styles.hTxt}>广东广州</Text>
                      <Text style={[styles.hI, { fontSize: 20 }]}>
                        &#xe9eb;
                      </Text>
                    </Animated.View>
                    <Animated.Text
                      style={[
                        styles.dropAddTxt,
                        {
                          opacity: bannerBgmColor,
                        },
                      ]}
                    >
                      &#xe68b;
                    </Animated.Text>
                  </Pressable>
                  <Animated.View
                    style={[
                      StyleSheet.compose(styles.nptBox, common.flexCol),
                      {
                        marginLeft: marginLeft,
                        marginTop: searchTop,
                      },
                    ]}
                  >
                    <SearchTxt />
                  </Animated.View>
                </View>
              )
            case 'swiper':
              return <HomeSwiper barHeight={barHeight} />
            case 'categoryMenu':
              return (
                <ImageBackground
                  source={require('../assets/images/menu-bgm.png')}
                  style={styles.menuWrapBgm}
                  imageStyle={styles.menuWrapImage}
                >
                  <View style={styles.menuBox}>
                    {menulist.map(item2 => (
                      <Pressable
                        onPress={() => goCategory(item2.id)}
                        style={styles.menuBlock}
                        key={item2.id}
                      >
                        <ImageBackground
                          source={
                            !item2.reverse
                              ? require('../assets/images/menu-icon-bgm.png')
                              : require('../assets/images/menu-icon-bgm2.png')
                          }
                          imageStyle={{ resizeMode: 'stretch' }}
                          style={[common.flexCol, styles.menuBgm]}
                        >
                          <Image
                            style={StyleSheet.compose(styles.menuIcon, {
                              marginRight: 4,
                            })}
                            resizeMode="contain"
                            source={item2.icon}
                          />
                          <Text style={styles.menuTxt}>{item2.txt}</Text>
                        </ImageBackground>
                      </Pressable>
                    ))}
                  </View>
                </ImageBackground>
              )
            case 'conditionWrap':
              return <ConditionWrap />
            case 'menuCard':
              return (
                <View style={styles.menuCard}>
                  <Image
                    source={require('../assets/images/menu-card-bgm.png')}
                    style={styles.menuCardBgm}
                  />
                  <View
                    style={StyleSheet.compose(
                      styles.menuCardTop,
                      common.flexCol,
                    )}
                  >
                    <Pressable
                      style={styles.menuItem}
                      onPress={goTab('RecommondTab')}
                    >
                      <Text style={styles.menuItmTl}>今日推荐</Text>
                      <TodayRecomment />
                    </Pressable>
                    <View style={styles.menuCardSplit} />
                    <Pressable
                      style={styles.menuItem}
                      onPress={goTab('ChildGoodTab')}
                    >
                      <Text style={styles.menuItmTl}>儿童用品</Text>
                      <ChildrenYongPing />
                    </Pressable>
                  </View>
                  <View
                    style={StyleSheet.compose(
                      styles.menuCardBtm,
                      common.flexCol,
                    )}
                  >
                    <Pressable
                      onPress={goTab('SpecialTab')}
                      style={styles.menuItem}
                    >
                      <View
                        style={StyleSheet.compose(
                          styles.menuBtmTWrap,
                          common.flexCol,
                        )}
                      >
                        <Text style={styles.menuItmTl}>限时特价</Text>
                        <Countdown />
                      </View>
                      <View style={styles.menuBtmBWrap}>
                        <Image
                          style={styles.menuBLImg}
                          source={require('../assets/coverImg/goods3.png')}
                        />
                        <Image
                          style={styles.menuBLImg}
                          source={require('../assets/coverImg/goods4.png')}
                        />
                      </View>
                    </Pressable>
                    <View style={styles.menuCardSplit} />
                    <View
                      style={StyleSheet.compose(
                        styles.menuItem,
                        common.flexCol,
                      )}
                    >
                      <Pressable
                        onPress={goTab('SelectGoodTab')}
                        style={StyleSheet.compose(
                          common.flexCol,
                          styles.menuBtmRWrap,
                        )}
                      >
                        <Image
                          source={require('../assets/icon/jingxuanhaowu-title.png')}
                          style={styles.menuBlkIconTitle}
                        />
                        <Image
                          source={require('../assets/icon/jingxuanhaowu.png')}
                          style={styles.menuBlkIcon}
                        />
                      </Pressable>
                      <Pressable
                        onPress={goTab('DiscountReductionTab')}
                        style={StyleSheet.compose(
                          common.flexCol,
                          styles.menuBtmRWrap,
                        )}
                      >
                        <Image
                          source={require('../assets/icon/discount-title.png')}
                          style={styles.menuBlkIconTitle}
                        />
                        <Image
                          source={require('../assets/icon/discount.png')}
                          style={styles.menuBlkIcon}
                        />
                      </Pressable>
                    </View>
                  </View>
                </View>
              )
            case 'listWrap':
              return <ListWrap ref={listWrapRef} />
            default:
              return <></>
          }
        }}
      />
    </>
  )
}
export default observer(Home)
const styles = StyleSheet.create({
  contain: {
    height: '100%',
  },
  header: {
    height: 50,
    width: '100%',
    zIndex: 1,
    position: 'relative',
    // backgroundColor: '#ffffffff'
  },
  headerBgm: {
    position: 'absolute',
    height: '100%',
    left: -12,
    top: 0,
    right: -12,
  },
  hTxt: {
    flex: 1,
    color: '#fff',
    fontSize: 14,
  },
  hI: {
    fontSize: 20,
    fontFamily: 'iconfont',
    color: '#fff',
  },
  dropAdd: {
    position: 'relative',
  },
  dropAddTxt: {
    fontFamily: 'iconfont',
    fontSize: 24,
    color: '#fff',
    position: 'absolute',
    left: 0,
    bottom: -14,
  },
  nptBox: {
    borderRadius: 16,
    marginTop: 6,
    backgroundColor: '#fff',
  },
  nptIBtn: {
    height: 28,
    width: 56,
    borderRadius: 14,
    marginLeft: 'auto',
  },
  nptIcon: {
    width: 14,
    height: 14,
    marginRight: 8,
  },
  nptITxt: {
    fontSize: 12,
    lineHeight: 26,
    height: '100%',
    color: '#fff',
    textAlign: 'center',
    textAlignVertical: 'center',
  },
  menuBox: {
    height: 112,
    width: '100%',
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'center',
    flexDirection: 'row',
    padding: 4,
  },
  menuWrapBgm: {
    marginLeft: 12,
    marginRight: 12,
    borderRadius: 6,
    backgroundColor: '#fff',
    height: 112,
    marginTop: -24,
  },
  menuWrapImage: {
    width: '100%',
    height: '100%',
    borderRadius: 6,
    resizeMode: 'stretch',
  },
  flexRowRDirection: {
    flexDirection: 'row-reverse',
  },
  flexRowDirection: {
    flexDirection: 'row',
  },
  menuBgm: {
    height: 36,
    width: 64,
    justifyContent: 'center',
  },
  menuBlock: {
    width: '25%',
    height: '50%',
    alignItems: 'center',
    justifyContent: 'center',
    display: 'flex',
  },
  menuIcon: {
    width: 14,
    height: 14,
  },
  menuTxt: {
    fontSize: 12,
    color: '#666',
    width: 26,
    lineHeight: 14,
  },
  menuCard: {
    borderRadius: 6,
    height: 254,
    backgroundColor: '#fff',
    marginTop: 12,
    marginLeft: 12,
    marginRight: 12,
    position: 'relative',
  },
  menuCardBgm: {
    height: 84,
    width: 156,
    resizeMode: 'contain',
    position: 'absolute',
  },
  menuCardTop: {
    height: 138,
    flex: 1,
    borderBottomWidth: 1,
    borderBottomColor: '#f1f1f1',
  },
  menuCardBtm: {
    height: 118,
  },
  menuCardSplit: {
    height: '100%',
    borderRightWidth: 1,
    borderColor: '#f1f1f1',
  },
  menuItem: {
    height: '100%',
    flex: 1,
    padding: 2,
  },
  menuBtmTWrap: {
    flexDirection: 'column',
  },
  menuBtmBWrap: {
    display: 'flex',
    alignItems: 'flex-end',
    flexDirection: 'row',
    justifyContent: 'center',
    paddingLeft: 4,
    paddingRight: 4,
    paddingBottom: 10,
  },
  menuBLImg: {
    height: 60,
    flex: 1,
    resizeMode: 'contain',
  },
  menuBLTxt: {
    fontSize: 12,
    width: 30,
  },
  menuItmTl: {
    fontSize: 14,
    color: '#333333',
    height: 30,
    lineHeight: 30,
    paddingLeft: 12,
    paddingTop: 4,
    fontWeight: 'bold',
    marginBottom: 10,
    paddingRight: 10,
  },
  menuBlkIcon: {
    width: 44,
    height: 44,
    resizeMode: 'contain',
  },
  menuBlkIconTitle: {
    height: 14,
    width: 66,
    marginBottom: 10,
    resizeMode: 'contain',
  },
  menuBtmRWrap: {
    flex: 1,
    paddingBottom: 22,
    paddingTop: 14,
    flexDirection: 'column',
    justifyContent: 'space-between',
    height: '100%',
  },
})
